<template>
  <div class="prdp-outer">
    <div class="prdp-main">
      <!-- 头部标题和状态指示器 -->
      <div class="prdp-title-bar">
        <h2>连退原料质量分析</h2>
        <div class="prdp-status-indicators">
          <div class="prdp-status-item">
            <span class="prdp-status-text">打滑</span>
            <span class="prdp-status-dot"></span>
          </div>
          <div class="prdp-status-item">
            <span class="prdp-status-text">碰撞</span>
            <span class="prdp-status-dot"></span>
          </div>
          <div class="prdp-status-item">
            <span class="prdp-status-text">性能分析</span>
            <span class="prdp-status-dot"></span>
          </div>
        </div>
      </div>
      <!-- 搜索区域 -->
      <div class="prdp-search-container">
        <el-form :inline="true" class="prdp-search-form">
          <el-form-item label="出入号查询">
            <el-input v-model="searchInput" placeholder="请输入查询内容"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="success" @click="handleExport">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 数据表格 -->
      <div class="prdp-table-container">
        <el-table :data="tableData" border style="width: 100%" :header-cell-style="headerStyle" height="100%">
          <el-table-column prop="steelGrade" label="钢种" width="100">
            <template #default="scope">
              <span>{{ scope.row.steelGrade === 0 ? 0 : (scope.row.steelGrade ?? '-') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="planNo" label="计划号" width="100">
            <template #default="scope">
              <span>{{ scope.row.planNo === 0 ? 0 : (scope.row.planNo ?? '-') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="inMatNo" label="入口卷号" width="150">
            <template #default="scope">
              <span>{{ scope.row.inMatNo === 0 ? 0 : (scope.row.inMatNo ?? '-') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="inMatWidth" label="入口材料宽度(mm)" width="150">
            <template #default="scope">
              <span>{{ scope.row.inMatWidth === 0 ? 0 : (scope.row.inMatWidth ?? '-') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="inMatThick" label="入口材料厚度(mm)" width="150">
            <template #default="scope">
              <span>{{ scope.row.inMatThick === 0 ? 0 : (scope.row.inMatThick ?? '-') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="inMatLen" label="入口材料长度(m)" width="140">
            <template #default="scope">
              <span>{{ scope.row.inMatLen === 0 ? 0 : (scope.row.inMatLen ?? '-') }}</span>
            </template>
          </el-table-column>

          <!-- 板形情况多级表头 -->
          <el-table-column label="板形情况" align="center">
            <el-table-column prop="ascHeadJifen" label="头部" width="100" align="center">
              <template #default="scope">
                <el-tooltip
                  v-if="scope.row.ascHeadJifen !== null && scope.row.ascHeadJifen !== undefined && !isNaN(scope.row.ascHeadJifen)"
                  :content="`当前值: ${scope.row.ascHeadJifen}`"
                  placement="top"
                >
                  <span :class="getGradeClassByScore(scope.row.ascHeadJifen)" class="grade-dot">
                    <span class="grade-letter">{{ getGradeLetterByScore(scope.row.ascHeadJifen) }}</span>
                    <span class="grade-circle">●</span>
                  </span>
                </el-tooltip>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="ascMidJifen" label="中部" width="100" align="center">
              <template #default="scope">
                <el-tooltip
                  v-if="scope.row.ascMidJifen !== null && scope.row.ascMidJifen !== undefined && !isNaN(scope.row.ascMidJifen)"
                  :content="`当前值: ${scope.row.ascMidJifen}`"
                  placement="top"
                >
                  <span :class="getGradeClassByScore(scope.row.ascMidJifen)" class="grade-dot">
                    <span class="grade-letter">{{ getGradeLetterByScore(scope.row.ascMidJifen) }}</span>
                    <span class="grade-circle">●</span>
                  </span>
                </el-tooltip>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="ascTailJifen" label="尾部" width="100" align="center">
              <template #default="scope">
                <el-tooltip
                  v-if="scope.row.ascTailJifen !== null && scope.row.ascTailJifen !== undefined && !isNaN(scope.row.ascTailJifen)"
                  :content="`当前值: ${scope.row.ascTailJifen}`"
                  placement="top"
                >
                  <span :class="getGradeClassByScore(scope.row.ascTailJifen)" class="grade-dot">
                    <span class="grade-letter">{{ getGradeLetterByScore(scope.row.ascTailJifen) }}</span>
                    <span class="grade-circle">●</span>
                  </span>
                </el-tooltip>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column prop="paopianRate" label="预测跑偏概率" width="120" align="center">
            <template #default="scope">
              <el-tooltip
                v-if="!isNaN(scope.row.paopianRate * 100)"
                :content="`预测跑偏概率: ${(scope.row.paopianRate * 100).toFixed(0)}%`"
                placement="top"
              >
                <span class="rate-container">
                  <span
                    :class="['rate-dot', scope.row.paopianRate * 100 > 50 ? 'rate-dot-red' : 'rate-dot-green']"
                  >●</span>
                  <span class="rate-text">{{ (scope.row.paopianRate * 100).toFixed(0) }}%</span>
                </span>
              </el-tooltip>
              <span v-else>-</span>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="scope">
              {{ formatISODate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="showDetail(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="prdp-pagination">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
            background layout="total, sizes, prev, pager, next, jumper" :total="totalItems"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>

      <!-- 详情弹窗 -->
      <el-dialog v-model="detailDialogVisible" :title="`出口卷号：${currentDetail.outboundNo}`" width="80%"
        class="prdp-detail-dialog" destroy-on-close @closed="handleDialogClose">
        <div class="prdp-detail-container">
          <!-- 钢卷基本信息 -->
          <div class="prdp-coil-info">
            <el-descriptions :column="6" border>
              <el-descriptions-item label="计划号" width="150px">{{ currentDetail.planContent }}</el-descriptions-item>
              <el-descriptions-item label="冷轧卷号" width="150px">{{ currentDetail.inboundNo }}</el-descriptions-item>
              <el-descriptions-item label="连退卷号" width="150px">{{ currentDetail.outboundNo }}</el-descriptions-item>
              <el-descriptions-item label="热卷号" width="150px">{{ currentDetail.coilNo }}</el-descriptions-item>
              <el-descriptions-item label="C" width="100px">0.0784</el-descriptions-item>
              <el-descriptions-item label="Si" width="100px">0.1272</el-descriptions-item>
              <el-descriptions-item label="Mn" width="100px">0.5207</el-descriptions-item>
              <el-descriptions-item label="P" width="100px">0.01935</el-descriptions-item>
              <el-descriptions-item label="S" width="100px">0.00378</el-descriptions-item>
              <el-descriptions-item label="板形预开始时间" width="180px">2024-03-05 00:59:42</el-descriptions-item>
              <el-descriptions-item label="板形预结束时间" width="180px">2024-03-05 01:05:17</el-descriptions-item>
              <el-descriptions-item label="记录时间" width="180px">2024-03-05 06:06:24</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 图表区域 -->
          <div class="prdp-charts-container">
            <div class="prdp-charts-row">
              <!-- 带钢凸度/横形图表 -->
              <div class="prdp-chart-item">
                <div class="prdp-chart-title">带钢凸度/横形 C40/W40(μm)</div>
                <div class="prdp-chart" ref="convexityChartRef"></div>
              </div>
              
              <!-- 平均板形图表 -->
              <div class="prdp-chart-item">
                <div class="prdp-chart-title">平均板形</div>
                <div class="prdp-chart" ref="avgShapeChartRef"></div>
              </div>
            </div>
            
            <div class="prdp-charts-row">
              <!-- 带钢厚度生产曲线图表 -->
              <div class="prdp-chart-item">
                <div class="prdp-chart-title">带钢厚度生产曲线</div>
                <div class="prdp-chart" ref="thicknessChartRef"></div>
              </div>
              
              <!-- 带钢板形二次判合系数图表 -->
              <div class="prdp-chart-item">
                <div class="prdp-chart-title">带钢板形二次判合系数</div>
                <div class="prdp-chart" ref="shapeCoefChartRef"></div>
              </div>
            </div>
          </div>
          
          <!-- 板形2D/3D视图 -->
          <div class="prdp-shape-view">
            <div class="prdp-shape-tabs">
              <div class="prdp-shape-tab prdp-shape-tab-active">带钢板形2D图</div>
              <div class="prdp-shape-tab">带钢板形3D图</div>
            </div>
            <div class="prdp-shape-content">
              <img src="https://via.placeholder.com/1200x220" alt="板形2D图" class="prdp-shape-img" />
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  MarkLineComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { ActualPerformanceRollDeviationApi } from '/@/api/deviationanalysis/ActualPerformanceRollDeviation'
// 注册ECharts组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
  MarkLineComponent
])
// 搜索相关
const searchInput = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const totalItems = ref(500)

// 表头样式
const headerStyle = {
  background: '#f5f7fa',
  color: '#333'
}

// 详情弹窗
const detailDialogVisible = ref(false)
const currentDetail = reactive({
  orderNo: '',
  productPlanNo: '',
  planContent: '',
  coilNo: '',
  inboundNo: '',
  outboundNo: '',
  steelGrade: ''
})

// 图表引用
const convexityChartRef = ref(null)
const avgShapeChartRef = ref(null)
const thicknessChartRef = ref(null)
const shapeCoefChartRef = ref(null)

// 图表实例
let convexityChart: echarts.ECharts | null = null
let avgShapeChart: echarts.ECharts | null = null
let thicknessChart: echarts.ECharts | null = null
let shapeCoefChart: echarts.ECharts | null = null

const tableData = ref([])
let timer: any = null

const fetchData = async () => {
  const res = await ActualPerformanceRollDeviationApi.findBySql({ keyName: 'paopian_pdi' })
  if (res && res.data && Array.isArray(res.data.data)) {
    tableData.value = res.data.data.map((item: any) => ({
      steelGrade: item.STEELGRADE || item.steelGrade,
      planNo: item.PLAN_NO || item.planNo,
      inMatNo: item.IN_MAT_NO || item.inMatNo,
      inMatWidth: item.IN_MAT_WIDTH || item.inMatWidth,
      inMatThick: item.IN_MAT_THICK || item.inMatThick,
      inMatLen: item.IN_MAT_LEN || item.inMatLen,
      ypClass: item.YP_CLASS || item.ypClass,
      exWidthClass: item.EX_WIDTH_CLASS || item.exWidthClass,
      exThkClass: item.EX_THK_CLASS || item.exThkClass,
      ascHeadJifen: item.ASC_HEAD_JIFEN || item.ascHeadJifen,
      ascMidJifen: item.ASC_MID_JIFEN || item.ascMidJifen,
      ascTailJifen: item.ASC_TAIL_JIFEN || item.ascTailJifen,
      ascDesc: item.ASC_DESC || item.ascDesc,
      paopianRate: item.PAOPIAN_RATE || item.paopianRate,
      createTime: item.CREATE_TIME || item.createTime,
    }))
  }
}

const startPolling = () => {
  fetchData()
  timer = setInterval(fetchData, 30000)
}
const stopPolling = () => {
  if (timer) clearInterval(timer)
  timer = null
}

onMounted(() => {
  startPolling()
})
onUnmounted(() => {
  stopPolling()
})

const handleSearch = () => {
  stopPolling()
  fetchData()
}

function formatISODate(dateString: string): string {
  const date = new Date(dateString);

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
  const day = String(date.getDate()).padStart(2, '0');

  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 处理重置事件
const handleReset = () => {
  searchInput.value = ''
  ElMessage.info('重置搜索条件')
}

// 处理导出事件
const handleExport = () => {
  ElMessage.success('数据导出成功')
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  // 实际应用中在这里重新加载数据
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  // 实际应用中在这里重新加载数据
}

// 根据等级获取样式类
// const getGradeClass = (grade: string) => {
//   switch (grade) {
//     case 'A': return 'prdp-grade-a'
//     case 'B': return 'prdp-grade-b'
//     case 'C': return 'prdp-grade-c'
//     case 'D': return 'prdp-grade-d'
//     default: return ''
//   }
// }

// 修改显示详情函数，确保每次打开弹窗时都重新初始化图表
const showDetail = (row: any) => {
  Object.assign(currentDetail, row)
  
  // 先销毁已存在的图表实例
  disposeCharts()
  
  detailDialogVisible.value = true
  
  // 在下一个DOM更新周期初始化图表
  nextTick(() => {
    initDetailCharts()
    create2DShapeView()
  })
}

// 创建2D形状视图
const create2DShapeView = () => {
  const shape2DContainer = document.querySelector('.prdp-shape-content')
  if (shape2DContainer) {
    // 清空容器
    shape2DContainer.innerHTML = ''
    
    // 创建2D热力图
    const heatmapCanvas = document.createElement('canvas')
    heatmapCanvas.width = 1000
    heatmapCanvas.height = 220
    heatmapCanvas.style.width = '100%'
    heatmapCanvas.style.height = 'auto'
    shape2DContainer.appendChild(heatmapCanvas)
    
    // 画热力图
    const ctx = heatmapCanvas.getContext('2d')
    if (ctx) {
      // 绘制热力图背景
      ctx.fillStyle = '#1a2754'
      ctx.fillRect(0, 0, heatmapCanvas.width, heatmapCanvas.height)
      
      // 左侧坐标刻度
      ctx.fillStyle = '#fff'
      ctx.font = '10px Arial'
      
      const scaleLabels = [
        'DS_FL_V01', 'FL_V57', 'FL_V53', 'FL_V49', 'FL_V45', 
        'FL_V41', 'FL_V37', 'FL_V33', 'FL_V29', 'FL_V25', 
        'FL_V21', 'FL_V17', 'FL_V13', 'FL_V09', 'FL_V05', 
        'OS_FL_V01'
      ]
      
      // 绘制刻度
      for (let i = 0; i < scaleLabels.length; i++) {
        const y = 20 + i * (heatmapCanvas.height - 40) / (scaleLabels.length - 1)
        ctx.fillText(scaleLabels[i], 5, y)
      }
      
      // 绘制热力图数据
      for (let x = 0; x < heatmapCanvas.width - 100; x++) {
        for (let y = 0; y < heatmapCanvas.height; y++) {
          // 生成不同的颜色值来模拟热力图
          const centerY = heatmapCanvas.height / 2
          let value = Math.abs(y - centerY) / centerY 
          value = Math.min(1, Math.max(0, 1 - value * 2))
          
          // 对边缘区域进行特殊处理，使其颜色更明显
          if (x < 50 || x > heatmapCanvas.width - 150) {
            value = Math.random() * 0.8 + 0.2
          } else {
            value = Math.random() * 0.6
          }
          
          // 颜色映射
          let color
          if (value > 4) {
            color = `rgb(255, 0, 0)` // 红色
          } else if (value > 3) {
            color = `rgb(255, 165, 0)` // 橙色
          } else if (value > 2) {
            color = `rgb(255, 255, 0)` // 黄色
          } else if (value > 1) {
            color = `rgb(173, 255, 47)` // 绿黄色
          } else {
            color = `rgb(0, 255, 255)` // 青色
          }
          
          // 绘制像素点
          ctx.fillStyle = color
          ctx.fillRect(x + 100, y, 1, 1)
        }
      }
      
      // 绘制x轴刻度
      ctx.fillStyle = '#fff'
      const xLabels = ['1088', '178', '36', '25', '74', '93', '112', '131', '150', '168', '187', '207', '239', '280', '321', '364', '412', '459', '507', '554', '602', '650', '697', '745', '793', '840', '888', '935', '983', '1031', '1075', '1102', '1122', '6']
      const step = (heatmapCanvas.width - 100) / (xLabels.length - 1)
      
      for (let i = 0; i < xLabels.length; i++) {
        const x = 100 + i * step
        ctx.fillText(xLabels[i], x - 10, heatmapCanvas.height - 5)
      }
      
      // 添加"长度(m)"标签
      ctx.fillText('长度(m)', heatmapCanvas.width - 40, heatmapCanvas.height - 5)
      
      // 绘制图例
      const legendLabels = ['>0.5', '0.25~0.5', '0.15~0.25', '0.05~0.15', '0~0.05', '0', '-0.05~0', '-0.05~-0.15', '-0.15~-0.25', '-0.25~-0.5', '<-0.5']
      const legendColors = ['#ff0000', '#ff6666', '#ffcc00', '#ccff00', '#ffffff', '#cccccc', '#99ffff', '#33ccff', '#0099ff', '#0066cc', '#003366']
      
      // 右侧图例
      for (let i = 0; i < legendLabels.length; i++) {
        const y = 20 + i * 18
        ctx.fillStyle = legendColors[i]
        ctx.fillRect(heatmapCanvas.width - 70, y - 10, 10, 10)
        ctx.fillStyle = '#fff'
        ctx.fillText(legendLabels[i], heatmapCanvas.width - 55, y)
      }
    }
  }
}

// 初始化详情页的图表
const initDetailCharts = () => {
  // 带钢凸度/横形图表
  if (convexityChartRef.value && !convexityChart) {
    convexityChart = echarts.init(convexityChartRef.value)
    convexityChart.setOption({
      backgroundColor: 'rgba(20, 32, 67, 0.6)',
      color: ['#00a0e9', '#ffba00'],
      legend: {
        data: ['C40', 'W40'],
        right: 10,
        textStyle: { color: '#fff' }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['1', '23', '45', '67', '89', '111', '133', '155', '177', '199', '221', '243', '265', '287', '309', '331', '353', '375', '397', '419', '441', '463', '485', '507'],
        axisLabel: { color: '#fff' },
        name: '长度(m)',
        nameLocation: 'end',
        nameTextStyle: { color: '#fff' }
      },
      yAxis: {
        type: 'value',
        axisLabel: { color: '#fff' },
        splitLine: { lineStyle: { type: 'dashed', color: 'rgba(255,255,255,0.2)' } }
      },
      series: [
        {
          name: 'C40',
          type: 'line',
          data: [60, 60, 90, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 90],
          symbol: 'none',
          smooth: true,
          lineStyle: {
            width: 2
          },
          areaStyle: {
            opacity: 0.2
          }
        },
        {
          name: 'W40',
          type: 'line',
          data: [0, 0, -5, -10, -10, -15, -20, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -35, -40, -40, -50],
          symbol: 'none',
          smooth: true,
          lineStyle: {
            width: 2
          },
          areaStyle: {
            opacity: 0.2
          }
        }
      ]
    })
  }
  
  // 平均板形图表
  if (avgShapeChartRef.value && !avgShapeChart) {
    avgShapeChart = echarts.init(avgShapeChartRef.value)
    avgShapeChart.setOption({
      backgroundColor: 'rgba(20, 32, 67, 0.6)',
      title: {
        text: '平均板形值',
        left: 'center',
        top: 10,
        textStyle: {
          color: '#fff',
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: '{b}: {c}'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['1085', '63', '134', '207', '354', '535', '716', '897', '1075'],
        axisLabel: { 
          color: '#fff',
          fontSize: 10
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        name: '长度(m)',
        nameLocation: 'end',
        nameTextStyle: { color: '#fff' }
      },
      yAxis: {
        type: 'value',
        axisLabel: { 
          color: '#fff',
          fontSize: 10
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        splitLine: { 
          lineStyle: { 
            type: 'dashed', 
            color: 'rgba(255, 255, 255, 0.1)' 
          } 
        },
        max: 5,
        min: 0
      },
      series: [
        {
          data: [2.1, 2.2, 2.3, 2.2, 2.1, 2.0, 2.0, 2.1, 2.3],
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            width: 3,
            color: '#4dc1ff'
          },
          itemStyle: {
            color: '#4dc1ff'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(77, 193, 255, 0.4)' },
              { offset: 1, color: 'rgba(77, 193, 255, 0.1)' }
            ])
          },
          markPoint: {
            symbol: 'pin',
            symbolSize: 40,
            data: [
              { type: 'max', name: '最大值' },
              { type: 'min', name: '最小值' }
            ],
            label: {
              color: '#fff'
            }
          },
          markLine: {
            lineStyle: {
              color: '#fff',
              type: 'dashed'
            },
            data: [
              { type: 'average', name: '平均值' }
            ],
            label: {
              color: '#fff',
              formatter: '平均: {c}'
            }
          }
        }
      ]
    })
  }
  
  // 带钢厚度生产曲线图表
  if (thicknessChartRef.value && !thicknessChart) {
    thicknessChart = echarts.init(thicknessChartRef.value)
    thicknessChart.setOption({
      backgroundColor: 'rgba(20, 32, 67, 0.6)',
      color: ['#00a0e9', '#ffba00', '#00c16e'],
      legend: {
        data: ['S强度', 'S增减', 'S速度'],
        right: 10,
        textStyle: { color: '#fff' }
      },
      grid: {
        left: '5%',
        right: '15%',
        bottom: '3%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['1085', '27', '63', '98', '134', '170', '207', '276', '354', '445', '535', '626', '716', '807', '897', '988', '1075', '1120'],
        axisLabel: { color: '#fff' },
        name: '长度(m)',
        nameLocation: 'end',
        nameTextStyle: { color: '#fff' },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '强度',
          nameTextStyle: { color: '#fff' },
          position: 'left',
          axisLabel: { color: '#fff' },
          splitLine: { show: false },
          axisLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.3)'
            }
          }
        },
        {
          type: 'value',
          name: '增减',
          nameTextStyle: { color: '#fff' },
          position: 'right',
          axisLabel: { color: '#fff' },
          splitLine: { show: false },
          axisLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.3)'
            }
          }
        },
        {
          type: 'value',
          name: '速度',
          nameTextStyle: { color: '#fff' },
          position: 'right',
          offset: 80,
          axisLabel: { color: '#fff' },
          splitLine: { show: false },
          axisLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.3)'
            }
          }
        }
      ],
      series: [
        {
          name: 'S强度',
          type: 'line',
          yAxisIndex: 0,
          data: [0.1, 0.2, 0, -0.1, -0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.1, 0.2],
          symbol: 'none',
          smooth: true,
          lineStyle: {
            width: 2
          }
        },
        {
          name: 'S增减',
          type: 'line',
          yAxisIndex: 1,
          data: [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3.5],
          symbol: 'none',
          smooth: true,
          lineStyle: {
            width: 2
          }
        },
        {
          name: 'S速度',
          type: 'line',
          yAxisIndex: 2,
          data: [-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3],
          symbol: 'none',
          smooth: true,
          lineStyle: {
            width: 2
          }
        }
      ]
    })
  }
  
  // 带钢板形二次判合系数图表
  if (shapeCoefChartRef.value && !shapeCoefChart) {
    shapeCoefChart = echarts.init(shapeCoefChartRef.value)
    shapeCoefChart.setOption({
      backgroundColor: 'rgba(20, 32, 67, 0.6)',
      color: ['#00a0e9', '#ffba00'],
      legend: {
        data: ['一次判据', '二次判据'],
        right: 10,
        textStyle: { color: '#fff' }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['1085', '27', '63', '98', '134', '170', '207', '276', '354', '445', '535', '626', '716', '807', '897', '988', '1075', '1120'],
        axisLabel: { color: '#fff' },
        name: '长度(m)',
        nameLocation: 'end',
        nameTextStyle: { color: '#fff' },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: { color: '#fff' },
        splitLine: { lineStyle: { type: 'dashed', color: 'rgba(255,255,255,0.2)' } },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        }
      },
      series: [
        {
          name: '一次判据',
          type: 'line',
          data: [-3, -2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2],
          symbol: 'none',
          smooth: true,
          lineStyle: {
            width: 2
          }
        },
        {
          name: '二次判据',
          type: 'line',
          data: [2, 2.5, 1.5, 0, 0, 0, 0.5, 1, 1.5, 0, -0.5, 0, 1, 1.5, 1, 0, 2, 4],
          symbol: 'none',
          smooth: true,
          lineStyle: {
            width: 2
          }
        }
      ]
    })
  }
}

// 销毁所有图表实例
const disposeCharts = () => {
  if (convexityChart) {
    convexityChart.dispose()
    convexityChart = null
  }
  if (avgShapeChart) {
    avgShapeChart.dispose()
    avgShapeChart = null
  }
  if (thicknessChart) {
    thicknessChart.dispose()
    thicknessChart = null
  }
  if (shapeCoefChart) {
    shapeCoefChart.dispose()
    shapeCoefChart = null
  }
}

// 监听弹窗关闭事件，确保销毁图表
const handleDialogClose = () => {
  disposeCharts()
}

// 监听窗口大小变化，调整图表
const handleResize = () => {
  convexityChart?.resize()
  avgShapeChart?.resize()
  thicknessChart?.resize()
  shapeCoefChart?.resize()
}

onMounted(() => {
  const res = ActualPerformanceRollDeviationApi.findBySql({
    "keyName": "paopian_pdi"
  })
  console.log(res)
  window.addEventListener('resize', handleResize)
})

const getGradeClassByScore = (score: number) => {
  if (score === null || score === undefined || isNaN(score)) return '-'
  if (score >= 1 && score <= 2) return 'grade-b'
  if (score >= 2 && score <= 3) return 'grade-c'
  if (score >= 3) return 'grade-d'
  return 'grade-a'
}

const getGradeLetterByScore = (score: number) => {
  if (score === null || score === undefined || isNaN(score)) return '-'
  if (score >= 1 && score <= 2) return 'B'
  if (score >= 2 && score <= 3) return 'C'
  if (score >= 3) return 'D'
  return 'A'
}

const contentRef = ref<HTMLElement | null>(null)
function resizeContent() {
  nextTick(() => {
    const outer = document.querySelector('.parameter-input-outer') as HTMLElement
    const inner = contentRef.value
    if (outer && inner) {
      const scale = Math.min(
        outer.clientHeight / inner.scrollHeight,
        outer.clientWidth / inner.scrollWidth,
        1
      )
      inner.style.transform = `scale(${scale})`
      inner.style.marginTop = scale < 1 ? `${(outer.clientHeight - inner.scrollHeight * scale) / 2}px` : '0'
    }
  })
}
onMounted(() => {
  window.addEventListener('resize', resizeContent)
  resizeContent()
})
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeContent)
})

</script>

<style scoped>
.prdp-outer {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(to top, #eaf1fb 0%, #2c69e8 100%);
  overflow: hidden;
}
.prdp-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  padding: 20px;
}
.prdp-table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}
.el-table {
  flex: 1;
  height: 100% !important;
  min-height: 0;
}
.prdp-pagination {
  margin-top: 10px;
}
.prdp-title-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.prdp-title-bar h2 {
  margin: 0;
  color: #333;
}

.prdp-status-indicators {
  display: flex;
  gap: 20px;
}

.prdp-status-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.prdp-status-text {
  color: #333;
  font-size: 14px;
}

.prdp-status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #67c23a;
  display: inline-block;
}

.prdp-search-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.prdp-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 等级指示器样式 */
.prdp-grade-indicator {
  display: flex;
  justify-content: center;
}

.prdp-grade-a {
  color: #67c23a;
  font-weight: bold;
}

.prdp-grade-b {
  color: #409eff;
  font-weight: bold;
}

.prdp-grade-c {
  color: #e6a23c;
  font-weight: bold;
}

.prdp-grade-d {
  color: #f56c6c;
  font-weight: bold;
}

.prdp-rate-indicator {
  text-align: center;
}

/* 详情弹窗样式 */
:deep(.prdp-detail-dialog .el-dialog__header) {
  background-color: #1a237e;
  padding: 10px 20px;
  margin-right: 0;
}

:deep(.prdp-detail-dialog .el-dialog__title) {
  color: #fff;
  font-size: 16px;
}

:deep(.prdp-detail-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: #fff;
}

:deep(.prdp-detail-dialog .el-dialog__body) {
  padding: 0;
}

.prdp-detail-container {
  padding: 15px;
  max-height: 80vh;
  overflow-y: auto;
}

.prdp-coil-info {
  margin-bottom: 20px;
}

:deep(.prdp-coil-info .el-descriptions__label) {
  background-color: #f5f7fa;
  color: #333;
}

.prdp-charts-container {
  margin-bottom: 20px;
}

.prdp-charts-row {
  display: flex;
  margin-bottom: 20px;
  gap: 20px;
}

.prdp-chart-item {
  flex: 1;
  min-height: 280px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  overflow: hidden;
}

.prdp-chart-title {
  padding: 10px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e6e6e6;
}

.prdp-chart {
  height: 240px;
}

.prdp-shape-view {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  overflow: hidden;
}

.prdp-shape-tabs {
  display: flex;
  background-color: #f5f7fa;
}

.prdp-shape-tab {
  padding: 10px 15px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
}

.prdp-shape-tab-active {
  color: #1a237e;
  border-bottom: 2px solid #1a237e;
  font-weight: bold;
}

.prdp-shape-content {
  padding: 10px;
  min-height: 200px;
  background-color: #fff;
}

.prdp-shape-img {
  width: 100%;
  height: auto;
  display: block;
}

.grade-dot {
  display: inline-flex;
  align-items: center;
  gap: 2px;
  cursor: pointer;
  height: 26px;
}

.grade-letter {
  font-size: 14px;
  font-weight: bold;
  line-height: 26px;
}

.grade-circle {
  font-size: 26px;
  line-height: 1;
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 4px;
}

.grade-a { color: #67c23a; }
.grade-b { color: #409eff; }
.grade-c { color: #e6a23c; }
.grade-d { color: #f56c6c; }

.rate-container {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.rate-dot {
  font-size: 26px;
  line-height: 1;
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 4px;
}

.rate-text {
  font-size: 14px;
  line-height: 26px;
}

.rate-dot-red { color: #f56c6c; }
.rate-dot-green { color: #67c23a; }
</style>
